/*
 * Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.cloudapp.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.TextView;

import com.huawei.cloudapp.R;
import com.huawei.cloudapp.common.CASLog;
import com.huawei.cloudapp.common.CasConnectInfo;
import com.huawei.cloudapp.common.CasHistory;
import com.huawei.cloudapp.utils.CasCommonUtils;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.Arrays;
import java.util.UUID;

public class CasCloudMainActivity extends Activity {

    private static final String TAG = "CasCloudMainActivity";
    private AutoCompleteTextView mCloudPhoneIp;
    private AutoCompleteTextView mCloudPhonePort;
    private TagFlowLayout mFlowLayout;
    private CasHistory mCasHistory;
    private Button appConnect;
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("com.huawei.cloudapp.ui.CasCloudPhoneActivity.destroyed")) {
                appConnect.setEnabled(true);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cas_cloud_main);
        mCasHistory = new CasHistory(getSharedPreferences("input_history", MODE_PRIVATE));
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();

        initAutoCompleteTextView("ip", mCloudPhoneIp);
        initAutoCompleteTextView("port", mCloudPhonePort);
        setAdapter(mFlowLayout);
        registerReceiver(mBroadcastReceiver,
                new IntentFilter("com.huawei.cloudapp.ui.CasCloudPhoneActivity.destroyed"));
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mBroadcastReceiver);
    }

    private void initView() {
        mCloudPhoneIp = findViewById(R.id.cloud_phone_ip);
        initAutoCompleteTextView("ip", mCloudPhoneIp);
        mCloudPhonePort = findViewById(R.id.cloud_phone_port);
        initAutoCompleteTextView("port", mCloudPhonePort);
        mFlowLayout = findViewById(R.id.flow);
        setAdapter(mFlowLayout);
        appConnect = findViewById(R.id.cloud_phone_connect);

    }

    public void cloudPhoneConnect(View view) {
        if (CasCommonUtils.isFastClick()) {
            return;
        }
        appConnect.setEnabled(false);
        startCloudPhoneActivity(CasCloudPhoneActivity.class);
    }


    public void cloudPhoneConnectWeb(View view) {
        if (CasCommonUtils.isFastClick()) {
            return;
        }
        startCloudPhoneActivity(CasCloudPhoneWebActivity.class);
    }

    private void startCloudPhoneActivity(Class<?> cls) {
        String phoneIp = mCloudPhoneIp.getText().toString().trim();
        if (TextUtils.isEmpty(phoneIp)) {
            CASLog.e(TAG, "输入Ip为空");
            appConnect.setEnabled(true);
            return;
        }
        String phonePort = mCloudPhonePort.getText().toString().trim();
        if (TextUtils.isEmpty(phonePort)) {
            CASLog.e(TAG, "输入Port为空");
            appConnect.setEnabled(true);
            return;
        }
        Intent intent = new Intent(CasCloudMainActivity.this, cls);
        CasConnectInfo connectorInfo = getCasConnectorInfo(phoneIp, phonePort);
        intent.putExtra(CasConnectInfo.BUNDLE_KEY, connectorInfo);
        startActivity(intent);
        overridePendingTransition(0, 0);
    }

    private CasConnectInfo getCasConnectorInfo(String phoneIp, String phonePort) {
        String sessionId = UUID.randomUUID().toString().replaceAll("-", "");
        CasConnectInfo connectorInfo = new CasConnectInfo();
        connectorInfo.setConnectIp(phoneIp);
        connectorInfo.setConnectPort(phonePort);
        connectorInfo.setBackgroundTimeout("60");
        connectorInfo.setAvailablePlayTime("4800");
        connectorInfo.setSessionId(sessionId);
        connectorInfo.setTicket("ticket_xxxxxx");
        // 32位16进制数，测试使用
        connectorInfo.setAesKey("11111111111111111111111111111111");
        connectorInfo.setAuthTs("987654321");
        connectorInfo.setTouchTimeout("0");
        return connectorInfo;
    }

    private void initAutoCompleteTextView(String key, AutoCompleteTextView autoCompleteTextView) {
        String[] keyHistoryList = mCasHistory.getHistory(key);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, keyHistoryList);
        autoCompleteTextView.setAdapter(adapter);
        autoCompleteTextView.setDropDownHeight(450);
        autoCompleteTextView.setCompletionHint("仅显示最近的10条记录");
        autoCompleteTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dropDownItem(view);
            }
        });
        autoCompleteTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    dropDownItem(view);
                }
            }
        });
        InputFilter filter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                for (int i = start; i < end; i++) {
                    char c = source.charAt(i);
                    if (!Character.isDigit(c) && c != '.') {
                        return "";
                    }
                }
                return null;
            }
        };
        autoCompleteTextView.setFilters(new InputFilter[]{filter});
    }

    private void dropDownItem(View view) {
        AutoCompleteTextView autoCompleteTextView = ((AutoCompleteTextView) view);
        if (autoCompleteTextView.getAdapter().getCount() != 0) {
            autoCompleteTextView.showDropDown();
        } else {
            autoCompleteTextView.dismissDropDown();
        }
    }

    private void setAdapter(TagFlowLayout flowLayout) {
        String[] data = mCasHistory.getHistory("ip:port");
        if (data.length == 0) return;
        flowLayout.setAdapter(new TagAdapter<String>(data) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView textView = (TextView) View.inflate(CasCloudMainActivity.this, R.layout.flow_item, null);
                textView.setText(s);
                return textView;
            }

            @Override
            public void onSelected(int position, View view) {
                String[] ipAndPortStr = data[position].split(":");
                mCloudPhoneIp.setText(ipAndPortStr[0]);
                mCloudPhonePort.setText(ipAndPortStr[1]);
                Log.e(TAG, "ipAndPortStr : "+ Arrays.toString(ipAndPortStr));
            }
        });
    }
}